package net.zjitc.controller;

import net.zjitc.Resultinfo.ResultInfo;
import net.zjitc.pojo.Category;
import net.zjitc.pojo.Product;
import net.zjitc.service.CategoryService;
import net.zjitc.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/product/")
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;
    @GetMapping("/findAll")
    public String findAll(Model model){
        List<Product> list = productService.findAll();
        model.addAttribute("plist",list);
        return "product/list";
    }

    @PostMapping("/add")
    public String add(Product product){
        int result = productService.add(product);
        return "redirect:/product/findAll";
    }


    @GetMapping("/editUI")
    public String editUI(Integer id,Model model){
        //准备商品信息
        Product prodcut =   productService.findById(id);
        //准备分类列表信息
        List<Category> clist = categoryService.findAll();
        model.addAttribute("product",prodcut);
        model.addAttribute("clist",clist);
        return "product/edit";

    }
    //修改商品
    @PostMapping("/update")
    public String update(Product product) {
        int num =  productService.update(product);
        //更新完后显示列表信息
        return "redirect:/product/findAll";
    }
    @PostMapping("/updateAjax")
    @ResponseBody
    public ResultInfo updateAjax(Product product) {
        int num =  productService.update(product);
        ResultInfo<Object> info = new ResultInfo<>();
        if (num>0){
            info.setMessage("修改成功！");
        }else {
            info.setMessage("修改失败！");
        }
        return info;
    }

    @PostMapping("/delete")
    @ResponseBody
    public ResultInfo delete(int[] ids) {
        int num =  productService.delete(ids);
       ResultInfo<Object> info = new ResultInfo<>();
        if (num>0){
            info.setFlag(true);
            info.setMessage("删除成功！");
        }else {
            info.setMessage("删除失败！");
            info.setFlag(false);
        }
        return info;
    }

}
